package top.fengyulou.qmy.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.fengyulou.common.Jr;
import top.fengyulou.common.UserUtils;
import top.fengyulou.common.WebUtils;
import top.fengyulou.config.SysConfig;
import top.fengyulou.qmy.entity.UserForm;
import top.fengyulou.qmy.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private SysConfig sysConfig;

    @GetMapping(SysConfig.INDEX)
    public String login(){
        return "login";
    }

    /**
     * 用户登录
     */
    @PostMapping("/user/ajax/login")
    @ResponseBody
    public Jr ajaxLogin(HttpServletRequest request, UserForm form) {
        //验证数据
        if (StringUtils.isBlank(form.getLoginName()) || StringUtils.isBlank(form.getPassword())) {
            return Jr.no("账号或密码错误");
        }
        //登录操作
        Jr login = userService.login(form);
        if (login.isStatus()) {
            UserUtils.login(request, login.getData());
        }
        return login;
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @GetMapping("/user/exit")
    public String exit(HttpServletRequest request) {
        UserUtils.exit(request);
        return WebUtils.redirect(sysConfig.getDomainName(), SysConfig.INDEX);
    }
}
